Page({
  /**
   * 页面的初始数据
   */
  data: {
    checked: false,
    animationAddressMenu: {},
    addressMenuIsShow: false,
    value: [0, 0, 0],
    region: [], // 选中的数据
    userid: '',
    consigneeName: "",
    phone: "",
    country: "",
    isDefault: 0, // 是否为默认地址值0
    detailedAddress: "",
    labelList: ["家", "公司", "学校"], //标签
    labelDefault: 0, // 标签默认,
    addressId: "",
  
  },

  /**
   * 详情页面 设置默认地址的请求
   * @param {*} event 
   */
  toggleCheckbox(event) {
    this.setData({
      checked: !this.data.checked
    });

    var that = this;
    var addressId = this.data.addressId; // 获取地址ID
    console.log("详情页面 ，获取地址ID：" + addressId);
    if (addressId === '') return; // 如果地址ID为0则不发送请求
    var isDefault = this.data.checked ? 1 : 0; // 如果勾选了就设为1，否则设为0
    console.log("如果勾选了就设为1，否则设为0: "+isDefault)

    if (isDefault === 1 ) {
      wx.request({
        url: `https://199shq.com/api/address/isDefault/${addressId}`,
        method: 'PUT',
        header: {
          'Content-Type': 'application/json',
          'token': wx.getStorageSync('token')
        },
        data: {
          isDefault: isDefault
        },
        success: function (res) {
          wx.showToast({
            title: '设置成功',
            icon: 'success',
            duration: 2000
          });
        },
        fail: function (error) {
          console.log(error);
        }
      });
    } else {
      // 发起取消默认地址的请求
      wx.request({
        url: `https://199shq.com/api//address/isDefault/cancel/${addressId}`,
        method: 'PUT',
        header: {
          'Content-Type': 'application/json',
          'token': wx.getStorageSync('token')
        },
        data: {
          isDefault: isDefault
        },
        success: function (res) {
          wx.showToast({
            title: '取消成功',
            icon: 'success',
            duration: 2000
          });
        },
        fail: function (error) {
          console.log(error);
        }
      });
    }
   

  },

  bindRegionChange: function (e) {
    console.log(e.detail.value);
    console.log(e.detail.code);
    this.setData({
      region: e.detail.value
    });
  },

  consigneeNameInput: function (e) {
    this.setData({
      consigneeName: e.detail.value
    });
  },

  phoneInput: function (e) {
    this.setData({
      phone: e.detail.value
    });
  },

  detailedAddressInput: function (e) {
    this.setData({
      detailedAddress: e.detail.value
    });
  },

  chooseLabelSelect: function (e) {
    const index = e.currentTarget.dataset.index;
    if (index === undefined || index === null) {
      this.setData({
        labelDefault: index
      });
      return;
    }
    if (index === this.data.labelDefault) {
      console.warn("Label already selected:", index);
      return;
    }
    this.setData({
      labelDefault: index
    });
  },

  /**
   * onSave 是处理修改地址的
   */
  onSave: function () {
    var app = getApp();
    var wxUserId = app.globalData.userInfo.wxUserId;
    console.log("onSave处理修改地址的：" + wxUserId);
    var consigneeName = this.data.consigneeName;
    console.log(consigneeName);
    var phone = this.data.phone;
    console.log(phone);
    const [province, city, country] = this.data.region;
    console.log(province, city, country);
    var detailedAddress = this.data.detailedAddress;
    console.log("初始详情地址" + detailedAddress);
    var addressId = this.data.addressId;
    var isDefault = this.data.isDefault;
    var label = this.data.labelDefault;

    if (consigneeName === "") {
      wx.showToast({
        title: '请输入姓名',
        image: "../../images/4-2商户.png"
      });
      return false;
    } else if (phone === "") {
      wx.showToast({
        title: '请输入手机号码',
        image: "../../images/4-2商户.png"
      });
      return false;
    }
    if (!/^1[3456789]\d{9}$/.test(phone)) {
      wx.showToast({
        title: '请输入正确的手机号码',
        image: '../../images/4-2商户.png'
      });
      return false;
    } else if (this.data.region.length === 0) {
      wx.showToast({
        title: '请选择所在地区',
        image: "../../images/4-2商户.png"
      });
      return false;
    } else if (detailedAddress === "") {
      wx.showToast({
        title: '请输入详细地址',
        image: "../../images/4-2商户.png"
      });
      return false;
    }


    // 构造要发送给后台的数据对象
    var data = {
      wxUserId: wxUserId,
      consignee: consigneeName,
      mobile: phone,
      province: province,
      city: city,
      country: country,
      details: detailedAddress,
      addressId: addressId,
      // isDefault: isDefault,
      label: label
    };

    // 发起修改 网络请求将数据发送到后台
    wx.request({

      url: 'https://199shq.com/api/address',
      method: 'PUT',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      data: data,
      success: function (res) {
        console.log(data);
        // 后台返回成功的处理代码
        console.log('数据存储成功');
        wx.navigateBack({
          delta: 1, // 返回上一页
          success: function () {
            // 在上一页调用onLoad方法更新信息
            var pages = getCurrentPages();
            var prevPage = pages[pages.length - 1]; // 当前页面为栈中最后一个页面
            prevPage.onLoad({
              value: data
            }); // 传递需要更新的信息
          }
        });
        
        

      },
      fail: function (res) {
        // 后台返回失败的处理代码
        console.error('数据存储失败', res);
      }
    });
  },

  /**
   * submit 是处理新增地址
   */
  submit: function () {
    var app = getApp();
    var wxUserId = app.globalData.userInfo.wxUserId;
    console.log("submit处理新增地址的wxUserId：" + wxUserId);
    var consigneeName = this.data.consigneeName;
    console.log(consigneeName);
    var phone = this.data.phone;
    console.log(phone);
    const [province, city, country] = this.data.region;
    console.log(province, city, country);
    var detailedAddress = this.data.detailedAddress;
    console.log("submit初始详情地址" + detailedAddress);
    var addressId = this.data.addressId;
    var isDefault = this.data.isDefault;
    var labelDefault = this.data.labelDefault;

    if (consigneeName === "") {
      wx.showToast({
        title: '请输入姓名',
        image: "../../images/4-2商户.png"
      });
      return false;
    } else if (phone === "") {
      wx.showToast({
        title: '请输入手机号码',
        image: "../../images/4-2商户.png"
      });
      return false;
    }
    if (!/^1[3456789]\d{9}$/.test(phone)) {
      wx.showToast({
        title: '请输入正确的手机号码',
        image: '../../images/4-2商户.png'
      });
      return false;
    } else if (this.data.region.length === 0) {
      wx.showToast({
        title: '请选择所在地区',
        image: "../../images/4-2商户.png"
      });
      return false;
    } else if (detailedAddress === "") {
      wx.showToast({
        title: '请输入详细地址',
        image: "../../images/4-2商户.png"
      });
      return false;
    }
    // 调用触发事件默认地址的方法
    var isDefault = this.data.checked ? 1 : 0; // 如果勾选了就设为1，否则设为0
    console.log("新增收货地址发起的设置默认的请求 2："+isDefault)

    // 构造要发送给后台的数据对象
    var data = {
      wxUserId: wxUserId,
      consignee: consigneeName,
      mobile: phone,
      province: province,
      city: city,
      country: country,
      details: detailedAddress,
      isDefault: isDefault,
      label: labelDefault

    };

    // 发起新增 网络请求将数据发送到后台
    wx.request({

      url: 'https://199shq.com/api/address/insert',
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      data: data,
      success: function (res) {
        console.log(data);
        // 后台返回成功的处理代码
        console.log('数据存储成功');
        wx.navigateBack({
          delta: 1, // 返回上一页
          success: function () {
            
            // 在上一页调用onLoad方法更新信息
            var pages = getCurrentPages();
            var prevPage = pages[pages.length - 1]; // 当前页面为栈中最后一个页面
            prevPage.onLoad({
              value: data
            }); // 传递需要更新的信息
          }
        });
        
      },
      fail: function (res) {
        // 后台返回失败的处理代码
        console.error('数据存储失败', res);
      }
    });
  },




  /**
   * 生命周期函数--监听页面加载,点击修改的时候拿取数据
   */
  onLoad: function (options) {
    
    var app = getApp();
    // 获取全局变量 
    var userInfo = app.globalData.userInfo.wxUserId;
    // 使用全局变量
    console.log("查看全局的用户id：" + userInfo);
    console.log("获取全局变量的信息：" + app.globalData.userInfo.wxUserId);

    // 修改地址
    var address = null;
    if (options.address) {
      try {
        address = JSON.parse(decodeURIComponent(options.address));
        console.log("拿取json之后的属性:" + address);
      } catch (error) {
        console.error('Failed to parse address:', error);
      }
    }
    // 根据地址数据设置相应的变量
    var consigneeName = ""; // 初始化 consigneeName 变量
    var phone = ""; // 初始化 phone 变量
    var region = []; // 初始化 region 变量
    var detailedAddress = ""; // 初始化 detailedAddress 变量
    var country = ""; // 初始化 country 变量
    var isDefault = 0; // 初始化 isDefault 变量 （是否为默认地址)
    var addressId = ""; // 初始化addressId变量
    var labelDefault = 0; // 初始化labelDefault变量

    if (address) {
      consigneeName = address.consignee;
      phone = address.mobile;
      region = [address.province, address.city, address.country];
      detailedAddress = address.details;
      country = address.country;
      isDefault = address.isDefault;
      addressId = address.addressId;
      labelDefault = address.label;
    }

    // 在这里可以对地址进行进一步处理和展示
    console.log(address);
    console.log(consigneeName);
    console.log(phone);
    console.log(region);
    console.log(detailedAddress);
    console.log(country);
    console.log("是否为默认地址1 0不是：" + isDefault);
    console.log("addressId为：" + addressId);
    console.log("labelDefault"+labelDefault);

    // 如果获取到的是默认地址为1，修改地址详情会勾选
    if (isDefault == 1) {
      this.setData({
        checked: true
      });
    }

    // 将数据赋值给对应的变量
    this.setData({
      consigneeName: consigneeName,
      phone: phone,
      region: region,
      detailedAddress: detailedAddress,
      country: country,
      isDefault: isDefault,
      addressId: addressId,
      labelDefault: labelDefault

    });
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'linear',
    })
    this.animation = animation
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})